package edu.spec.wechat.kit;

import edu.spec.wechat.model.WechatFianlValue;
import edu.spec.wechat.web.WechatContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.madgecko.basic.util.JsonUtil;
import org.madgecko.basic.util.PropertiesUtil;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by MadFrog on 2016/10/26.
 */
public class WechatKit {

    /**
     * 将微信接口地址中的"Access_Token"为真实的access_token
     * @param url 包含"Access_Token"的微信接口地址
     * @return 真实完整的url
     */
    public static String replaceAccessToken(String url){
        return url.replace("ACCESS_TOKEN", WechatContext.getAccessToken());
    }

    public static void setWechatContext(){
        Properties props = PropertiesUtil.getInstance().load("wechat_basic");
        WechatContext wc = WechatContext.getInstance();
        // 常规公众号
        if(props.getProperty("test_mode").equals("false")){
            wc.setAppID(props.getProperty("appId"));
            wc.setAppsecrect(props.getProperty("appsecret"));
        }else if(props.getProperty("test_mode").equals("true")) {
            // 公众账号测试
            wc.setAppID(props.getProperty("test_appId"));
            wc.setAppsecrect(props.getProperty("test_appsecret"));
        }
        wc.setBaseurl(props.getProperty("base_url"));
        wc.setBasetoken(props.getProperty("base_token"));
    }

    /**
     * 向微信服务器特定接口发送POST请求
     * @param url 微信服务器接口
     * @param data json或xml文本
     * @param contentType post内容的类型"application/json"或xml
     * @return
     */
    public static String sendPost(String url, String data, String contentType){
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.addHeader("Content-type", contentType);
            //默认编码是"ISO-8859-1"，改为"UTF-8"后就不会乱码了
            StringEntity entity = new StringEntity(data, ContentType.create(contentType, "UTF-8"));
            post.setEntity(entity);
            resp = client.execute(post);
            int statusCode = resp.getStatusLine().getStatusCode();
            if(statusCode>=200&&statusCode<300){
                String se = EntityUtils.toString(resp.getEntity());
                return se;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null){
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 使用情况不多，一种微信验证服务器，另一种是查询
     * @param url
     * @return
     */
    public static String sendGet(String url){
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            resp = client.execute(get);
            int statusCode = resp.getStatusLine().getStatusCode();
            if(statusCode>=200&&statusCode<300){
                String se = EntityUtils.toString(resp.getEntity(), "UTF-8");
                return se;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(client!=null){
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public static String getOpenIdByCode(String code){
        try {
            String url = WechatFianlValue.AUTH_GET_OPENID;
            url = url.replace("APPID", WechatContext.getInstance().getAppID())
                    .replace("SECRET", WechatContext.getInstance().getAppsecrect())
                    .replace("CODE", code);
            String json = WechatKit.sendGet(url);
            //取出的结果形式带双引号，"oj_WLv8dyQzZeoetVw-o9-nTotKY"，需去除。
            String openId = JsonUtil.getMapper().readTree(json).get("openid").toString().replace("\"", "");
            return openId;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
